package com.business.controller;

import com.comm.config.TopicRabbitConfig;
import com.comm.context.LoginUserContext;
import com.comm.entity.po.LoginUserInfo;
import com.comm.enums.LoginUserErrorEnum;
import com.comm.exception.BusinessException;
import com.comm.result.ResponseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Description: TODO
 * @Author: mis_wu
 * @Date: 2022/7/20
 *
 **/
@RestController
@RequestMapping("/business")
@Api("用户操作控制器")
@Slf4j
public class UserController {

    @Autowired
    RedisTemplate<Object,Object> redisTemplate;

    @Value("${spring.application.name}")
    private String businessName;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @PostMapping("/toLogin")
    @ApiOperation("用户登录操作")
    ResponseResult<LoginUserInfo> userLoginVerify(@RequestBody LoginUserInfo loginUserInfo){
        log.info("中台用户登录接口:{}",loginUserInfo);
        if (ObjectUtils.isEmpty(loginUserInfo)){
            throw new BusinessException(LoginUserErrorEnum.USER_LOGIN_INFO_NOT_NULL.getDesc());
        }
        if (loginUserInfo.getUsername().equals("admin") && loginUserInfo.getPassword().equals("123")){
            String token = UUID.randomUUID().toString().replaceAll("-","");
            loginUserInfo.setToken(token);
            redisTemplate.opsForValue().set("login-user",loginUserInfo,1, TimeUnit.DAYS);
            log.info("redis保存成功...");
            LoginUserContext.mock(loginUserInfo);
            return ResponseResult.isSuccess(loginUserInfo);
        }
        return ResponseResult.error(new LoginUserInfo(),LoginUserErrorEnum.USER_NAME_PASSWORD_ERROR.getDesc());
    }

    @GetMapping("/sendRabbitMessage")
    public ResponseResult<Object> sendRabbitMessage(){
        ResponseResult<Object> result = new ResponseResult<>("1000","business provider message",
                "生产者服务 I am "+businessName+" service,hello stranger server !!!");
        rabbitTemplate.convertAndSend(TopicRabbitConfig.BUSINESS_TOPIC_EXCHANGE_NAME,TopicRabbitConfig.BUSINESS_TOPIC_KEY,result);
        return ResponseResult.isSuccess("business server data send success ...");
    }

}
